const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const logger = require('morgan');

const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const wxRouter = require('./routes/wx');

const WxApi = require('./lib/wx.api')
const WxConfig = require('./lib/wx.config.json')

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
//cookieSession 必须放在cookieParser后面
app.use(cookieSession({
    //session的秘钥，防止session劫持。 这个秘钥会被循环使用，秘钥越长，数量越多，破解难度越高。
    keys: ['nevermore', 'eminem', 'sorry510'],
    //session过期时间，1小时
    maxAge: 60 * 60 * 1000, 
    //可以改变浏览器cookie的名字
    name: 'wx-session'
}));

app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter)
// app.use('/users', usersRouter)

// 验证微信通信
app.use('/wx_check', (req, res, next)=> {
	// get方式，4个参数
	// signature	微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
	// timestamp	时间戳
	// nonce	随机数
	// echostr	随机字符串
	let query = req.query

	let signature = query.signature || ''
	let nonce = query.nonce || ''
	let timestamp = query.timestamp || ''

  	let isOK = WxApi.checkSignature(signature, nonce, timestamp, WxConfig.token)
  	if(isOK) res.send(query.echostr)
  	else res.send('error')
})

// 中间件,获取微信access_token
app.use('/wx', (req, res, next)=> {
	WxApi.getAccessToken()
		.then(accessToken=> {
			// access_token
            WxApi.getJsapiTicket(accessToken)
                .then(jsapiTicket=> {
                    req.wx = {}
                    req.wx.config = WxConfig
                    req.wx.accessToken = accessToken
                    req.wx.jsapiTicket = jsapiTicket
                    next()
                })
                .catch(err => {
                    console.log(err)
                    next()
                })
		})
		.catch(err=> {
			console.log(err)
			next()
		})
})

app.use('/wx', wxRouter)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404))
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
